package com.gmail.blackdog1987.carcare.adapter;

import in.srain.cube.image.CubeImageView;
import in.srain.cube.image.ImageLoader;
import in.srain.cube.image.ImageLoaderFactory;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.gmail.blackdog1987.carcare.App;
import com.gmail.blackdog1987.carcare.R;
import com.gmail.blackdog1987.carcare.entity.TMaintain;

public class MeiRongAdapter extends BaseAdapter {

	List<TMaintain> datas;
	Context mContext;
	ImageLoader imageLoader;

	public MeiRongAdapter(Context context, List<TMaintain> datas) {
		this.datas = datas;
		this.mContext = context;
		imageLoader = ImageLoaderFactory.create(mContext);
	};

	public void addDatas(List<TMaintain> datas) {
		this.datas.addAll(datas);
	}

	public void setDatas(List<TMaintain> datas) {
		if (this.datas == null) {
			this.datas = new ArrayList<TMaintain>();
		}
		this.datas.clear();
		this.datas.addAll(datas);
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {

		return datas == null ? 0 : datas.size();
	}

	@Override
	public TMaintain getItem(int position) {
		return datas == null ? null : datas.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		final TMaintain m = getItem(position);
		if (convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(R.layout.item_meirong, null);
			holder = new ViewHolder();
			holder.mHead = (CubeImageView) convertView.findViewById(R.id.maintain_head);
			holder.mLocation = (TextView) convertView.findViewById(R.id.maintain_location);
			holder.mDistance = (TextView) convertView.findViewById(R.id.maintain_weihu);
			holder.mName = (TextView) convertView.findViewById(R.id.maintain_name);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.mLocation.setText(String.valueOf(m.getLocation()));
		if (App.location != null) {
			holder.mDistance.setText("距离"
					+ String.valueOf((int)DistanceUtil.getDistance(new LatLng(App.location.getLatitude(), App.location.getLongitude()),
							new LatLng(m.getLat(), m.getLon()))/1000) + "公里");
		}
		holder.mName.setText(m.getTitle());
		if (m.headurl != null && m.headurl.length() != 0) {
			holder.mHead.loadImage(imageLoader, m.headurl);
		}
		convertView.setTag(holder);
		return convertView;
	}

	public class ViewHolder {
		TextView mName;
		TextView mLocation;
		TextView mDistance;
		CubeImageView mHead;
	}

}
